
package com.yimixian.app.rest.api;

import android.text.TextUtils;
import android.util.Log;

import com.yimixian.app.cart.CartManager;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.SharePreferenceKeys;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.model.Address;
import com.yimixian.app.model.CartDeliverGoodsGroup;
import com.yimixian.app.model.CartUpdate;
import com.yimixian.app.model.CartUpdateDescription;
import com.yimixian.app.model.CartUpdateGoodsGroup;
import com.yimixian.app.model.CartUpdateTotal;
import com.yimixian.app.model.GoodsItem;
import com.yimixian.app.model.SearchKeyResult;
import com.yimixian.app.model.Store;
import com.yimixian.app.util.SharedPreferencesHelper;

import org.json.JSONArray;
import org.json.JSONObject;

import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.client.Response;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by songzy on 2015/10/12.
 */
public class CartUpdateAPI extends YmxBaseAPI<CartUpdate> {
    public static final String CART_UPDATE = "/v5/cart/sync";
    public static final String CART_GET = "/v5/cart/flush";
    public static final String CART_REMOVE = "/v5/cart/remove";

    public static final String CART_UPDATE_API = "cart_update_api";

    public static final String CART_SYNC_NOT_LOGIN_API = "/v5/cart/sync_not_login";

    public int mGoodId;
    public int mTrend;
    public int mRemoveGoodId;

    /**
     * @param callback
     */
    public CartUpdateAPI(Callback<Response> callback) {
        super(callback);
    }
    //默认0：非购物车内点击添加商品
    public void getCartUpdate() {
        /*String token = DataManager.getInstance().get(CacheKeys.TOKEN);
        int trend = mTrend;
        int goodId = mGoodId;
        Address address = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
        if (address != null && !TextUtils.isEmpty(address.storeId)) {
            int storeId = Integer.parseInt(address.storeId);
            if (storeId > 0 || address.id > 0) {
                int addressId = address.id;
                mYmxRestService.getCartUpdate(token, goodId, trend, addressId, storeId, mCallback);
            } else {
                EventBus.getDefault().postSticky(new String(Constants.EVENT_BUS_DISSMISS_DIALOG));
            }
        } else {
            EventBus.getDefault().postSticky(new String(Constants.EVENT_BUS_DISSMISS_DIALOG));
        }*/
        getCartUpdate(0);
    }
    public void getCartUpdate(int shoppingCart) {
        String token = DataManager.getInstance().get(CacheKeys.TOKEN);
        int trend = mTrend;
        int goodId = mGoodId;
        Address address = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
        if (address != null && !TextUtils.isEmpty(address.storeId)) {
            int storeId = Integer.parseInt(address.storeId);
            if (storeId > 0 || address.id > 0) {
                int addressId = address.id;
                mYmxRestService.getCartUpdate(token, goodId, trend, addressId, storeId, shoppingCart, mCallback);
            } else {
                EventBus.getDefault().postSticky(new String(Constants.EVENT_BUS_DISSMISS_DIALOG));
            }
        } else {
            EventBus.getDefault().postSticky(new String(Constants.EVENT_BUS_DISSMISS_DIALOG));
        }
    }
    public boolean hasNeedsParams;
    public void getCartInfo() {
        String token = DataManager.getInstance().get(CacheKeys.TOKEN);
        Address address = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
        if (address != null && !TextUtils.isEmpty(address.storeId)) {
            int storeId = Integer.parseInt(address.storeId);
            if (storeId > 0 || address.id > 0) {
                hasNeedsParams = true;
                int addressId = address.id;
                mYmxRestService.getCartInfo(token, addressId, storeId, mCallback);
            } else {
                hasNeedsParams = false;
                EventBus.getDefault().postSticky(new String(Constants.EVENT_BUS_DISSMISS_DIALOG));
            }
        } else {
            hasNeedsParams = false;
            EventBus.getDefault().postSticky(new String(Constants.EVENT_BUS_DISSMISS_DIALOG));
        }
    }

    public void removeCartItem() {
        String token = DataManager.getInstance().get(CacheKeys.TOKEN);
        Address address = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
        if (address != null && !TextUtils.isEmpty(address.storeId)) {
            int storeId = Integer.parseInt(address.storeId);
            if (storeId > 0 || address.id > 0) {
                int goodId = mRemoveGoodId;
                int addressId = address.id;
                mYmxRestService.removeCartItem(token, addressId, storeId, goodId, mCallback);
            } else {
                EventBus.getDefault().postSticky(new String(Constants.EVENT_BUS_DISSMISS_DIALOG));
            }
        } else {
            EventBus.getDefault().postSticky(new String(Constants.EVENT_BUS_DISSMISS_DIALOG));
        }
    }

    @Override
    public String getRelativeURL() {
        return CART_UPDATE;
    }

    @Override
    public CartUpdate parseJson(JSONObject jsonObject) {
        if(CartManager.getInstance().mCartGoodsItems!=null)CartManager.getInstance().mCartGoodsItems.clear();
        System.out.println("哈利路亚清2****");
        CartUpdate cartUpdate = new CartUpdate();
        Store store = new Store(0, "");
        if (jsonObject != null) {
            cartUpdate.notice = jsonObject.optString("notice");
            if(jsonObject.optJSONObject("data")!=null)jsonObject = jsonObject.optJSONObject("data");
            JSONObject storeObj = jsonObject.optJSONObject("store");
//            if(storeObj==null)storeObj = jsonObject.optJSONObject("data").optJSONObject("store");
            if (storeObj != null) {
                store.id = storeObj.optInt("id");
//                store.name = storeObj.optString("name");
                store.cannotDeliverText = storeObj.optString("cannot_deliver_text");
                store.deliveryFee = storeObj.optInt("delivery_fee");
                store.deliveryZoneUrl = storeObj.optString("delivery_zone_url");
                store.freeDeliveryPrice = storeObj.optInt("free_delivery_price");
            }

            JSONArray delGoodsGroupsJsonArray = jsonObject.optJSONArray("deliveries_groups");
//            if(delGoodsGroupsJsonArray==null)delGoodsGroupsJsonArray = jsonObject.optJSONObject("data").optJSONArray("deliveries_groups");
            if (delGoodsGroupsJsonArray != null) {
                List<CartDeliverGoodsGroup> deliverGoodsGroups = new ArrayList<>();
                for (int i = 0; i < delGoodsGroupsJsonArray.length(); i++) {
                    //配送方式分类
                    CartDeliverGoodsGroup mCartDeliverGoodsGroup = new CartDeliverGoodsGroup();

                    CartUpdateTotal total = new CartUpdateTotal();
                    JSONObject goodsGroupObj = delGoodsGroupsJsonArray.optJSONObject(i);

                    JSONObject totalObj = goodsGroupObj.optJSONObject("total");
                    if (totalObj != null) {
                        total.count = totalObj.optInt("count");
                        total.price = totalObj.optDouble("price");
                        List<CartUpdateDescription> desc = new ArrayList<>();
                        JSONArray descJsonArray = totalObj.optJSONArray("desc");
                        if (descJsonArray != null) {
                            for (int m = 0; m < descJsonArray.length(); m++) {
                                CartUpdateDescription description = new CartUpdateDescription();
                                JSONObject descObj = descJsonArray.optJSONObject(m);
                                if (descObj != null) {
                                    description.color = descObj.optString("color");
                                    description.content = descObj.optString("content");
                                    description.fontsize = descObj.optInt("font_size");
                                }
                                desc.add(description);
                            }
                        }
                        total.desc = desc;

                        List<CartUpdateDescription> simpleDesc = new ArrayList<>();
                        JSONArray simpleDescJsonArray = totalObj.optJSONArray("simple_desc");
                        if (simpleDescJsonArray != null) {
                            for (int m = 0; m < simpleDescJsonArray.length(); m++) {
                                CartUpdateDescription description = new CartUpdateDescription();
                                JSONObject descObj = simpleDescJsonArray.optJSONObject(m);
                                if (descObj != null) {
                                    description.color = descObj.optString("color");
                                    description.content = descObj.optString("content");
                                    description.fontsize = descObj.optInt("font_size");
                                }
                                simpleDesc.add(description);
                            }
                        }
                        total.simpleDesc = simpleDesc;

                        JSONObject object = totalObj.optJSONObject("need_buy");
                        if (object == null) total.isNeedBuy = false;
                        else{
                            total.isNeedBuy = true;
                            total.but_name = object.optString("but_name");
                            total.pici = object.optString("pici");
                        }

                        total.giftDesc = totalObj.optString("gift_desc");
                    }
                    long groupId = goodsGroupObj.optLong("group_id");
                    mCartDeliverGoodsGroup.groupId = groupId;
                    String groupTitle = goodsGroupObj.optString("group_name");
                    mCartDeliverGoodsGroup.groupTitle = groupTitle;
                    JSONArray goodsGroupJsonArray = goodsGroupObj.optJSONArray("groups");
                    List<CartUpdateGoodsGroup> goodsGroup = new ArrayList<>();
                    if (goodsGroupJsonArray != null) {
                        for (int k = 0; k < goodsGroupJsonArray.length(); k++) {
                            JSONObject object = goodsGroupJsonArray.optJSONObject(k);
                            if (object != null) {
                                CartUpdateGoodsGroup mCartUpdateGoodsGroup = new CartUpdateGoodsGroup();
                                List<GoodsItem> goods = new ArrayList<>();
                                JSONArray goodsArray = object.optJSONArray("goods");
                                String deliverTitle = object.optString("title");
                                if (goodsArray != null) {
                                    for (int j = 0; j < goodsArray.length(); j++) {
                                        GoodsItem goodsItem = new GoodsItem();
                                        JSONObject goodsItemObj = goodsArray.optJSONObject(j);
                                        if (goodsItemObj != null) {
                                            goodsItem.groupId = groupId;
                                            goodsItem.groupTitle = groupTitle;
                                            goodsItem.deliverTitle = deliverTitle;
                                            goodsItem.simpleDesc = total.simpleDesc;
                                            goodsItem.isNeedBuy = total.isNeedBuy;
                                            goodsItem.but_name = total.but_name;
                                            goodsItem.pici = total.pici;
                                            goodsItem.giftDesc = total.giftDesc;
                                            goodsItem.id = goodsItemObj.optInt("id");
                                            goodsItem.name = goodsItemObj.optString("name");
                                            goodsItem.unitDesc = goodsItemObj.optString("unit_desc");
                                            goodsItem.unitPrice = goodsItemObj.optString("unit_price");
                                            goodsItem.shouldBuyCount = goodsItemObj.optInt("should_buy_count");
                                            goodsItem.count = String.valueOf(goodsItemObj.optInt("count"));
                                            goodsItem.imgRatio = (float) goodsItemObj.optDouble("img_ratio");
                                            goodsItem.img = goodsItemObj.optString("img");
                                            goodsItem.promotionImg = goodsItemObj.optString("promotion_img");
                                            goodsItem.descUrl = goodsItemObj.optString("desc_url");
                                            goodsItem.isActivated = goodsItemObj.optBoolean("is_activated");
                                            goodsItem.tips = goodsItemObj.optString("tips");
                                            goodsItem.countZeroReason = goodsItemObj.optString("count_zero_reason");
                                            goodsItem.canNotBuyReason = goodsItemObj.optString("can_not_buy_reason");
                                            goods.add(goodsItem);
                                        }
                                        if (goodsItem != null && CartManager.getInstance().mCartGoodsItems != null) {
                                            CartManager.getInstance().mCartGoodsItems.put(goodsItem.id, goodsItem);
                                        }
                                    }
                                }
                                mCartUpdateGoodsGroup.title = deliverTitle;
                                mCartUpdateGoodsGroup.goods = goods;
                                CartManager.getInstance().updateAddCartGoodsItem(goods);
                                goodsGroup.add(mCartUpdateGoodsGroup);
                            }
                        }
                        mCartDeliverGoodsGroup.totalDesc = total;
                        mCartDeliverGoodsGroup.goodsGroup = goodsGroup;
                    }
                    deliverGoodsGroups.add(mCartDeliverGoodsGroup);
                }
                cartUpdate.store = store;
                cartUpdate.delieverGoodsGroup = deliverGoodsGroups;
            }

            CartUpdateTotal total = new CartUpdateTotal();
            //           total.count = totalObj.optInt("count");
            total.totalPrice = jsonObject.optString("total_price");
            total.count = jsonObject.optInt("total_count");
            //                total.simpleDesc = totalObj.optString("simple_desc");
            JSONArray descJsonArray = jsonObject.optJSONArray("total_price_desc");
            if (descJsonArray != null) {
                List<CartUpdateDescription> desc = new ArrayList<>();
                for (int i = 0; i < descJsonArray.length(); i++) {
                    CartUpdateDescription description = new CartUpdateDescription();
                    JSONObject descObj = descJsonArray.optJSONObject(i);
                    if (descObj != null) {
                        description.color = descObj.optString("color");
                        description.content = descObj.optString("content");
                        description.fontsize = descObj.optInt("font_size");
                    }
                    desc.add(description);
                }
                total.desc = desc;
            }
            long revision = jsonObject.optLong("revision");
            cartUpdate.total = total;
            cartUpdate.revision = revision;
        }
        return cartUpdate;
    }

    //    @Override
    //    public CartUpdate parseJson(JSONObject jsonObject) {
    //        CartUpdate cartUpdate = new CartUpdate();
    //        Store store = new Store(0, "");
    //        List<CartUpdateGoodsGroup> goodsGroups = new ArrayList<>();
    //        CartUpdateTotal total = new CartUpdateTotal();
    //        List<CartUpdateDescription> desc = new ArrayList<>();
    //        if (jsonObject != null) {
    //            JSONObject storeObj = jsonObject.optJSONObject("store");
    //            if (storeObj != null) {
    //                store.id = storeObj.optInt("id");
    ////                store.name = storeObj.optString("name");
    ////                store.cannotDeliverText = storeObj.optString("cannot_deliver_text");
    ////                store.deliveryFee = storeObj.optInt("delivery_fee");
    ////                store.deliveryZoneUrl = storeObj.optString("delivery_zone_url");
    ////                store.freeDeliveryPrice = storeObj.optInt("free_delivery_price");
    //            }
    //            JSONArray goodsGroupsJsonArray = jsonObject.optJSONArray("good_groups");
    //            if(goodsGroupsJsonArray != null) {
    //                for (int i = 0; i < goodsGroupsJsonArray.length(); i++) {
    //                    CartUpdateGoodsGroup goodsGroup = new CartUpdateGoodsGroup();
    //                    JSONObject goodsGroupObj = goodsGroupsJsonArray.optJSONObject(i);
    //                    if (goodsGroupObj != null) {
    //                        goodsGroup.title = goodsGroupObj.optString("title");
    //                        List<GoodsItem> goods = new ArrayList<>();
    //                        JSONArray goodsArray = goodsGroupObj.optJSONArray("goods");
    //                        if (goodsArray != null) {
    //                            for (int j = 0; j < goodsArray.length(); j++) {
    //                                GoodsItem goodsItem = new GoodsItem();
    //                                JSONObject goodsItemObj = goodsArray.optJSONObject(j);
    //                                if (goodsItemObj != null) {
    //                                    goodsItem.id = goodsItemObj.optInt("id");
    //                                    goodsItem.name = goodsItemObj.optString("name");
    //                                    goodsItem.unitDesc = goodsItemObj.optString("unit_desc");
    //                                    goodsItem.unitPrice = goodsItemObj.optString("unit_price");
    //                                    goodsItem.shouldBuyCount = goodsItemObj.optInt("should_buy_count");
    //                                    goodsItem.count = String.valueOf(goodsItemObj.optInt("count"));
    //                                    goodsItem.imgRatio = (float) goodsItemObj.optDouble("img_ratio");
    //                                    goodsItem.img = goodsItemObj.optString("img");
    //                                    goodsItem.promotionImg = goodsItemObj.optString("promotion_img");
    //                                    goodsItem.descUrl = goodsItemObj.optString("desc_url");
    //                                    goodsItem.isActivated = goodsItemObj.optBoolean("is_activated");
    //                                    goodsItem.tips = goodsItemObj.optString("tips");
    //                                    goodsItem.countZeroReason = goodsItemObj.optString("count_zero_reason");
    //                                    goodsItem.canNotBuyReason = goodsItemObj.optString("can_not_buy_reason");
    //                                    goods.add(goodsItem);
    //                                }
    //                                if (goodsItem != null && CartManager.getInstance().mCartGoodsItems != null) {
    //                                    CartManager.getInstance().mCartGoodsItems.put(goodsItem.id, goodsItem);
    //                                }
    //                            }
    //                        }
    //                        goodsGroup.goods = goods;
    //                        CartManager.getInstance().updateAddCartGoodsItem(goods);
    //                    }
    //                    goodsGroups.add(goodsGroup);
    //                }
    //            }
    //            JSONObject totalObj = jsonObject.optJSONObject("total");
    //            if (totalObj != null) {
    //                total.count = totalObj.optInt("count");
    //                total.price = totalObj.optDouble("price");
    //                total.simpleDesc = totalObj.optString("simple_desc");
    //                JSONArray descJsonArray = totalObj.optJSONArray("desc");
    //                if(descJsonArray != null) {
    //                    for (int i = 0; i < descJsonArray.length(); i++) {
    //                        CartUpdateDescription description = new CartUpdateDescription();
    //                        JSONObject descObj = descJsonArray.optJSONObject(i);
    //                        if (descObj != null) {
    //                            description.color = descObj.optString("color");
    //                            description.content = descObj.optString("content");
    //                            description.fontsize = descObj.optInt("font_size");
    //                        }
    //                        desc.add(description);
    //                    }
    //                }
    //                total.desc = desc;
    //            }
    //            long revision = jsonObject.optLong("revision");
    //            cartUpdate.store = store;
    //            cartUpdate.goodsGroup = goodsGroups;
    //            cartUpdate.total = total;
    //            cartUpdate.revision = revision;
    //        }
    //        return cartUpdate;
    //    }
    public void syncUnLoginCartData(){
        String token = DataManager.getInstance().get(CacheKeys.TOKEN);
        int storeID = SharedPreferencesHelper.getInt(SharePreferenceKeys.STORE_ID);
        StringBuffer sb = new StringBuffer();
//        Object obj = SharedPreferencesHelper.getObject(SharePreferenceKeys.GOOD_J);
        if(TextUtils.isEmpty(token)||storeID==-1)return;
        sb.append("{");
//        JSONArray jsonArray;
        if(CartManager.offLineCartMap!=null&&CartManager.offLineCartMap.size()>0){
            HashMap<Integer, GoodsItem> map = CartManager.offLineCartMap;
//            jsonArray = new JSONArray();
            if(null!=map){
                for (Map.Entry<Integer,GoodsItem> entry:map.entrySet()){
//                    JSONObject jsonObject = new JSONObject();
                    try {

//                        jsonObject.put(entry.getKey()+"", entry.getValue());
//                        jsonArray.put(jsonObject);
                        sb.append("\""+entry.getKey()+"\""+":"+"\""+entry.getValue().count+"\""+",");
                    } catch (Exception e) {
                        e.printStackTrace();
                        return;
                    }

                }
                String s = sb.substring(0,sb.length()-1);
                s = s+"}";
//                sb.append("}");
//                String str = jsonArray.toString();
//                str = str.substring(1,str.length()-1);
                mYmxRestService.getCartSyncUnLogin(s,token,storeID,mCallback);
            }
        }
    }

}
